<?php

namespace app\api\controller\product;

use think\Controller;
use think\Cookie;

class Product extends Controller{
    public function __construct()
    {
        parent::__construct();

        $this->TypeModel=model('Product.Type');
        $this->ProductModel=model('Product.Product');
        $this->UserModel=model('User.User');
        $this->VipModel=model('Product.Vip');
    }

    public function index(){
        // 查询推荐商品
        $Recommend=$this->ProductModel->with(['type'])->where(['flag'=>3])->order('id','desc')->limit(5)->select();
        $News=$this->ProductModel->with(['type'])->where(['flag'=>1])->order('id','desc')->limit(4)->select();
        $Hot=$this->ProductModel->with(['type'])->where(['flag'=>2])->order('id','desc')->limit(6)->select();
        $Type=$this->TypeModel->limit(8)->select();

        // 封装数组
        $data=[
            'Recommend'=>$Recommend,//推荐商品
            'News'=>$News,//新品
            'Hot'=>$Hot,//热销
            'Type'=>$Type,//商品分类
        ];

        $this->success('返回首页数据',null,$data);
        exit;
    }

    // 商品列表
    public function type(){
        if($this->request->isPost()){
            $typeid=$this->request->param('typeid',0);
            $flag=$this->request->param('flag',0);
            $orderby=$this->request->param('orderby','id');
            $keywords=$this->request->param('keywords','');
            $where=[];

            // 先判断分类是否存在
            $type=$this->TypeModel->find($typeid);
            if($type){
                $where['typeid']=$typeid;
            }

            // 判断是否有选择属性
            if($flag){
                $where['flag']=$flag;
            }

            if(!empty($keywords)){
                $where['name']=['like',"%$keywords%"];
            }

            // 获取商品列表
            $prolist=$this->ProductModel->where($where)->order($orderby,'desc')->select();

            $this->success('查询商品数据成功',null,$prolist);
            exit;
        }
    }

    public function info(){
        if($this->request->isPost()){
            // 获取商品id
            $proid=$this->request->param('proid',0);
            $userid=$this->request->param('userid',0);

            // 查询商品的详细
            $product=$this->ProductModel->with(['type'])->find($proid);
            if(!$product){
                $this->error('商品不存在');
                exit;
            }

            $user=$this->UserModel->find($userid);
            $vip=isset($user) ? $user['vip'] : 0;

            if($vip > 0){
                $level=$this->VipModel->where(['proid'=>$proid,'level'=>$vip])->value('price');
                $product['level']=$level;
            }
            $this->success('返回商品详情',null,$product);
            exit;
        }
    }
}